package com.wanmait.myhouse.managerController;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@Controller
@RequestMapping("manager")
public class ManagerShowCaptchaController {
    @GetMapping("check")
    @ResponseBody
    public String check(String inputCode, HttpSession session){
        String code = (String) session.getAttribute("code");
        if (code.equalsIgnoreCase(inputCode)){
            return "1";
        }else {
            return "0";
        }
    }



    @GetMapping("captcha")
    @ResponseBody
    public void captcha(HttpServletResponse servletResponse,HttpSession session){
        Random random = new Random();
        String code = "";
        for (int i = 1; i <=4 ; i++) {
            int c = random.nextInt(123);
            if ((c>=48&&c<=57)||(c>=65&&c<=90)||(c>=97&&c<=122)){
                code += (char)c;
            }else {
                i--;
            }
        }
        session.setAttribute("code",code);
        BufferedImage image = new BufferedImage(100,50,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setFont(new Font("",Font.BOLD,25));
        graphics.drawString(code,15,45);
        try {
            OutputStream os = servletResponse.getOutputStream();
            ImageIO.write(image,"jpg",os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
